package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.dto.extra.SearchResultDto;
import com.lanjiu.lib.imclient.dto.user.RegisteredUserDto;
import com.lanjiu.lib.imclient.dto.user.TouristsUserDto;
import com.lanjiu.lib.imclient.ims.IMSClientHelper;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.NetUtils;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.SearchBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.FriendInfoView;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.ReadFinishCycTimeUtil;
import com.ljkj.cordial.chat.widget.BottomListPop;
import com.ljkj.cordial.chat.widget.PuzzleImageView;
import com.nic.view.util.JToast;
import com.nic.view.util.glide.GlideUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 好友信息页
 */
public class FriendInfoActivity extends AppEventActivity<FriendInfoView> {


    @BindView(R.id.iv_user)
    PuzzleImageView ivUser;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.ll_send_msg)
    LinearLayout tvSendMsg;
    @BindView(R.id.ll_modify_remark)
    LinearLayout llModifyRemark;
    @BindView(R.id.sw_read_finish_clear)
    SwitchCompat swReadFinishClear;
    @BindView(R.id.cb_read_finish_clear)
    CheckBox cbReadFinishClear;
    @BindView(R.id.tv_read_finish_clear)
    TextView tvReadFinishClear;
    @BindView(R.id.ll_read_finish_clear)
    LinearLayout llReadFinishClear;
    @BindView(R.id.sw_offline_msg)
    SwitchCompat swOfflineMsg;
    @BindView(R.id.cb_offline_msg)
    CheckBox cbOfflineMsg;
    @BindView(R.id.tv_delete_friend)
    TextView tvDeleteFriend;
    @BindView(R.id.tv_visitor_hint)
    TextView tvVisitorHint;
    @BindView(R.id.tv_modify_remark)
    TextView tvModifyRemark;
    @BindView(R.id.tv_read_finish)
    TextView tvReadFinish;
    @BindView(R.id.tv_offline_msg)
    TextView tvOfflineMsg;
    @BindView(R.id.ll_read_finish)
    LinearLayout llReadFinish;
    @BindView(R.id.ll_offline_msg)
    LinearLayout llOfflineMsg;
    @BindView(R.id.ll_add_to_friend)
    FrameLayout llAddToFriend;

    private int type;
    private String targetId;
    private String targetName;
    private String targetType;
    private String targetGroup;
    private FriendTable mFriendTable;
    private GroupMemberTable mGroupMemberTable;
    private boolean isInitiativeDelete;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_friend_info;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        type = getIntent().getIntExtra(Canstants.KEY_TYPE, Canstants.KEY_REGISTER);
        targetName = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_NAME);
        targetId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_ID);
        targetType = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_TYPE);
        targetGroup = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_GROUP);
        if (Canstants.KEY_VISITOR == type || Canstants.KEY_REGISTER == type) {
            tvVisitorHint.setVisibility(Canstants.KEY_VISITOR == type ? View.VISIBLE : View.INVISIBLE);
            if (Canstants.KEY_VISITOR == type) {
                llReadFinish.setVisibility(View.GONE);
            }
            getToolbarRightIv().setVisibility(View.VISIBLE);
        } else if (Canstants.KEY_GROUP_VISITOR == type) {
            // 群成员入口
            llReadFinish.setVisibility(View.GONE);
            llReadFinishClear.setVisibility(View.GONE);
            llOfflineMsg.setVisibility(View.GONE);
            tvDeleteFriend.setVisibility(View.GONE);
            tvSendMsg.setVisibility(View.GONE);
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Boolean>() {
                @Override
                public void onAction(Boolean obj) {
                    llAddToFriend.setVisibility(obj ? View.GONE : View.VISIBLE);
                }

                @Override
                public Boolean onThreadAction() {
                    return FriendTable.isExistFriendById(targetId);
                }
            });
        }

        ReadFinishCycTimeUtil.getInstance().setReadFinishCycTime(this, Canstants.getSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()), tvReadFinishClear);
//        ReadFinishCycTimeUtil.getInstance().setReadFinishCycChangeListener(this, Canstants.isSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()), swReadFinishClear, llReadFinishClear);
        ReadFinishCycTimeUtil.getInstance().setReadFinishCycChangeListener(this, Canstants.isSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()), cbReadFinishClear, llReadFinishClear);

        if (Canstants.KEY_GROUP_VISITOR == type) {
            mGroupMemberTable = GroupMemberTable.query(targetGroup, targetId);
            if (mGroupMemberTable != null) {
                mFriendTable = new FriendTable();
                mFriendTable.setFriendUserId(mGroupMemberTable.getGroupMemberUserId());
                mFriendTable.setFriendNickname(mGroupMemberTable.getGroupMemberName());
                mFriendTable.setFriendAvatar(mGroupMemberTable.getGroupMemberAvatar());
                mFriendTable.setFriendAvatarId(mGroupMemberTable.getGroupMemberAvatarId());
                mFriendTable.setFriendAlias(mGroupMemberTable.getGroupMemberAlias());
                mFriendTable.setUserType(mGroupMemberTable.getUserType());
                mFriendTable.setLoginUserId(UserPreferences.getUserId());
                ivUser.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlbumManageUtil.getInstance().downLoadFileFriendAvatar(mGroupMemberTable.getGroupMemberAvatar(), mGroupMemberTable.getGroupMemberUserId(), new AlbumManageUtil.OnFileResponse() {
                            @Override
                            public void onResult(String url, String path) {
                                if (!TextUtils.isEmpty(path)) {
                                    AlbumManageUtil
                                            .getInstance().lookLargePhoto(v.getContext(), path);
                                }

                            }
                        });
                    }
                });
            }
        } else {
            mFriendTable = FriendTable.getTableByFriendUserId(targetId);
        }
        if (mFriendTable != null) {
            if (!TextUtils.isEmpty(mFriendTable.getFriendAvatarPath())) {
                ivUser.setFriendPath(mFriendTable.getFriendAvatarPath(), mFriendTable.getFriendAvatar());
            } else {
                ivUser.setFriendUrl(mFriendTable.getFriendAvatar(), mFriendTable.getFriendUserId());
            }
            String remark = mFriendTable.getFriendAlias();
            if (!TextUtils.isEmpty(remark) && !remark.equals(mFriendTable.getFriendNickname())) {
                tvNickname.setText(remark);
                tvName.setVisibility(View.VISIBLE);
                tvName.setText("昵称:" + mFriendTable.getFriendNickname());
                tvId.setText("ID:" + mFriendTable.getFriendUserId());
            } else {
                tvNickname.setText(mFriendTable.getFriendNickname());
                tvId.setText("ID:" + mFriendTable.getFriendUserId());
            }

            boolean r = mFriendTable.getOfflineMessage();
//            swOfflineMsg.setChecked(r);
//            swOfflineMsg.setOnClickListener(v -> {
//                boolean isChecked = swOfflineMsg.isChecked();
//                obtainView().doSetFriendOfflineMsg(targetId, targetType, isChecked);
//            });
            cbOfflineMsg.setChecked(r);
            cbOfflineMsg.setEnabled(IMSClientHelper.getInstance().isConnected());
            cbOfflineMsg.setOnClickListener(v -> {
                if (NetUtils.isConnected(this)) {
                    boolean isChecked = cbOfflineMsg.isChecked();
                    obtainView().doSetFriendOfflineMsg(targetId, targetType, isChecked);
                } else {
                    cbOfflineMsg.setChecked(!cbOfflineMsg.isClickable());
                    JToast.showShort(this, "请检查网络状态");
                }
            });
            ivUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlbumManageUtil.getInstance().downLoadFileFriendAvatar(mFriendTable.getFriendAvatar(), mFriendTable.getFriendUserId(), new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onResult(String url, String path) {
                            if (!TextUtils.isEmpty(path)) {
                                AlbumManageUtil
                                        .getInstance().lookLargePhoto(v.getContext(), path);
                            }

                        }
                    });

                }
            });

        } else {
            finish();
            return;
        }
        getToolbarRightIv().setImageResource(R.mipmap.icon_elli);
        getToolbarRightIv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vv) {
                showDeleteDialog();
            }
        });
        isInitiativeDelete = false;

    }

    private void updateContactGroupMemberAlias(String alias) {
        ObserverThread.create().onBackGroudThread(new Runnable() {
            @Override
            public void run() {
                List<GroupMemberTable> list = GroupMemberTable.queryMembers(targetId);
                if (list != null && !list.isEmpty()) {
                    for (GroupMemberTable memberTable : list) {
                        memberTable.setGroupMemberAlias(alias);
                        GroupMemberTable.update(memberTable);
                    }
                }
                List<ChatTableBean> clist = ChatTableBean.query(targetGroup, targetId);
                if (clist != null && !clist.isEmpty()) {
                    for (ChatTableBean bean : clist) {
                        bean.setAlias(alias);
                        ChatTableBean.update(bean);
                    }
                }
                ChatContentTable q = ChatContentTable.queryRowByTargetId(targetId, Canstants.SINGLE_CHAT);
                if (q != null) {
                    q.setAlias(alias);
                    ChatContentTable.update(q);
                    MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.GROUP_REFRESH);
                    event.setData(targetId);
                    EventBus.getDefault().post(event);
                }

            }
        });

    }

    private void showDeleteDialog() {
        List<String> list = new ArrayList<>();
        list.add("删除好友");
        new BottomListPop(this).setList(list, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    obtainView().doDeleteFriend(targetId, targetType);
                }
            }
        }).show();
    }

    public static void jumpTo(Context context, int type, String targetName, String targetId, String targetType) {
        Intent intent = new Intent(context, FriendInfoActivity.class);
        intent.putExtra(Canstants.KEY_TYPE, type);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        context.startActivity(intent);
        ChatApp.getInstance().inActivityAnim(context);
    }

    public static void jumpToForResult(Activity context, int type, String targetName, String targetId, String targetType) {
        Intent intent = new Intent(context, FriendInfoActivity.class);
        intent.putExtra(Canstants.KEY_TYPE, type);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        context.startActivityForResult(intent, Canstants.MODIFT_TARGETNAME_CODE);
        ChatApp.getInstance().inActivityAnim(context);
    }


    public static void jumpTo(Activity context, String group, String targetName, String targetId) {
        String targetType = IMSUtils.userTypeAnalysis(targetId);
        Intent intent = new Intent(context, FriendInfoActivity.class);
        intent.putExtra(Canstants.KEY_TYPE, Canstants.KEY_GROUP_VISITOR);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_GROUP, group);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_NAME, targetName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_ID, targetId);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_TYPE, targetType);
        context.startActivityForResult(intent, Canstants.MODIFT_TARGETNAME_CODE);
        ChatApp.getInstance().inActivityAnim(context);
    }

    @OnClick({R.id.ll_send_msg, R.id.ll_modify_remark, R.id.ll_read_finish_clear, R.id.tv_delete_friend, R.id.ll_add_to_friend})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_send_msg:
                GroupChatActivity.jumpTo(view.getContext(), Canstants.SINGLE_CHAT, targetName, targetId, targetType);
                finish();
                break;
            case R.id.ll_modify_remark:
                if (Canstants.KEY_VISITOR == type) {
                    return;
                }
                if (Canstants.KEY_GROUP_VISITOR == type) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<String>() {
                        @Override
                        public void onAction(String currentUserMember) {
                            ModifyRemarkActivity.jumpToModifyGroupMemberAlias(FriendInfoActivity.this, targetGroup, currentUserMember, targetId);
                        }

                        @Override
                        public String onThreadAction() {
                            GroupMemberTable query = GroupMemberTable.query(targetGroup, UserPreferences.getUserId());
                            if (query != null)
                                return query.getGroupMemberId();
                            return null;
                        }
                    });
                } else {
                    ModifyRemarkActivity.jumpToModifyFriendAlias(this, targetId, targetType);
                }
                break;
            case R.id.ll_read_finish_clear:
//                if (Canstants.KEY_VISITOR == type) {
//                    return;
//                }
                ReadFinishCycTimeUtil.getInstance().showPop(this, Canstants.getSingleReadFinishKey(targetId, ChatApp.getInstance().getUserId()), tvReadFinishClear);
                break;
            case R.id.tv_delete_friend:
                showDeleteDialog();
                break;
            case R.id.ll_add_to_friend:
                if (mFriendTable == null) return;
                SearchBean search = new SearchBean();
                if (IMSContacts.UserType.REGISTERED_USER.equals(mFriendTable.getUserType())) {
                    search.setUserId(mFriendTable.getFriendUserId());
                } else {
                    search.setTouristId(mFriendTable.getFriendUserId());
                }
                search.setAvatars(mFriendTable.getFriendAvatar());
                search.setName(mFriendTable.getFriendNickname());
//                SearchResultActivity.jumpTo(this, Canstants.KEY_SEARCH_FRIEND, search);
                AddFriendActivity.jumpTo(this, Canstants.KEY_SEARCH_FRIEND, search);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Canstants.KEY_REMARK_RESULT == requestCode && Canstants.KEY_REMARK_RESULT == resultCode) {
            String remark = data.getStringExtra(Canstants.KEY_REMARK);
            if (!TextUtils.isEmpty(remark) && !targetName.equals(remark)) {
                tvNickname.setText(remark);
                tvName.setVisibility(View.VISIBLE);
                tvName.setText("昵称:" + mFriendTable.getFriendNickname());
                if (mFriendTable != null) {
                    mFriendTable.setFriendAlias(remark);
                    FriendTable.update(mFriendTable);
                    updateContactGroupMemberAlias(remark);
                }
            } else {
                if (!TextUtils.isEmpty(mFriendTable.getFriendAlias())) {
                    // 如果之前备注不为空，则表示现在改为空，需要刷新
                    updateContactGroupMemberAlias(remark);
                }
                tvNickname.setText(mFriendTable.getFriendNickname());
                tvName.setText(null);
                tvName.setVisibility(View.GONE);
            }
            setResult(Canstants.MODIFT_TARGETNAME_CODE, data);
        }
    }


    @Override
    protected boolean afterOnStartRegisterEventBus() {
        setShowDefNetDialog(false);
        obtainView().doGetFriendInfo(targetId);
        return super.afterOnStartRegisterEventBus();
    }

    @Override
    protected FriendInfoView bindNettyMessageView() {
        return new FriendInfoView(new FriendInfoView.FriendInfoCallback() {
            @Override
            public void onSetFriendOfflineMsgCallback(int code, String msg, FriendDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    String friendUserId;
                    boolean friendOfflineMsg;
                    if (data != null && !TextUtils.isEmpty(data.getFriendUserId())) {
                        friendUserId = data.getFriendUserId();
                        friendOfflineMsg = data.isOfflineMessage();
                    } else {
                        friendUserId = targetId;
                        friendOfflineMsg = swOfflineMsg.isChecked();
                    }
                    FriendTable t = FriendTable.getTableByFriendUserId(friendUserId);
                    if (t != null) {
                        t.setOfflineMessage(friendOfflineMsg);
                        DbController.getInstance().getWrite().getFriendTableDao().update(t);
                    }
                } else {
                    JToast.showShort(FriendInfoActivity.this, msg);
                    swOfflineMsg.setChecked(!swOfflineMsg.isChecked());
                }
            }

            @Override
            public void onDeleteFriendCallback(int code, String msg) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Boolean>() {
                        @Override
                        public void onAction(Boolean obj) {
                            isInitiativeDelete = true;
                            MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.DELETE_FRIEND);
                            event.setData(targetId);
                            EventBus.getDefault().post(event);
                            finish();
                        }

                        @Override
                        public Boolean onThreadAction() {
                            DeleteHistoryUtil.getInstance().deleteNavChat(targetId);
                            return null;
                        }
                    });

                } else {
                    JToast.showShort(FriendInfoActivity.this, msg);
                }
            }

            @Override
            public void onFriendInfoCallback(int code, String msg, FriendDto data) {
                if (code != IMSContacts.ResponseCode.SUCCESS || data == null) return;
                showNet(isShowDefNetDialog());
                ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<FriendTable>() {
                    @Override
                    public void onAction(FriendTable obj) {
                        mFriendTable = obj;
                        dismissNet(isShowDefNetDialog());
                        if (mFriendTable != null) {
                            swOfflineMsg.setChecked(mFriendTable.getOfflineMessage());
                            String remark = mFriendTable.getFriendAlias();
                            if (!TextUtils.isEmpty(mFriendTable.getFriendAvatarPath())) {
                                ivUser.setFriendPath(mFriendTable.getFriendAvatarPath(), mFriendTable.getFriendAvatar());
                            } else {
                                ivUser.setFriendUrl(mFriendTable.getFriendAvatar(), mFriendTable.getFriendUserId());
                            }
                            if (!TextUtils.isEmpty(remark) && !remark.equals(mFriendTable.getFriendNickname())) {
                                tvNickname.setText(remark);
                                tvName.setVisibility(View.VISIBLE);
                                tvName.setText("昵称:" + mFriendTable.getFriendNickname());
                                tvId.setText("ID:" + mFriendTable.getFriendUserId());
                                mFriendTable.setFriendAlias(remark);
                                FriendTable.update(mFriendTable);
                                updateContactGroupMemberAlias(remark);
                            } else {
                                tvNickname.setText(mFriendTable.getFriendNickname());
                                tvId.setText("ID:" + mFriendTable.getFriendUserId());
                            }
                            updateChatContentTable(mFriendTable);
                        }
                    }

                    @Override
                    public FriendTable onThreadAction() {
                        if (Canstants.KEY_GROUP_VISITOR == type && mGroupMemberTable != null) {
                            mGroupMemberTable.setGroupMemberUserId(data.getFriendUserId());
                            mGroupMemberTable.setGroupMemberAvatar(data.getFriendAvatar());
                            mGroupMemberTable.setGroupMemberName(data.getFriendNickname());
                            mGroupMemberTable.setUserType(IMSContacts.UserType.REGISTERED_USER);
                            if (mGroupMemberTable.getId() != null)
                                DbController.getInstance().getWrite().getGroupMemberTableDao().update(mGroupMemberTable);
                        }
                        FriendTable tableByFriendUserId = FriendTable.getRowByFriendUserIdNotNull(data.getFriendUserId());
                        tableByFriendUserId.setOfflineMessage(data.isOfflineMessage());
                        tableByFriendUserId.setFriendUserId(data.getFriendUserId());
                        tableByFriendUserId.setFriendAvatar(data.getFriendAvatar());
                        tableByFriendUserId.setFriendNickname(data.getFriendNickname());
                        tableByFriendUserId.setFriendAlias(data.getFriendAlias());
                        tableByFriendUserId.setUserType(IMSContacts.UserType.REGISTERED_USER);
                        if (tableByFriendUserId.getId() != null)
                            DbController.getInstance().getWrite().getFriendTableDao().update(tableByFriendUserId);
                        return tableByFriendUserId;
                    }
                });
            }
        });
    }

    private void updateChatContentTable(FriendTable mFriendTable) {
        AlbumManageUtil.getInstance().downLoadFileFriendAvatar(mFriendTable.getFriendAvatar(), mFriendTable.getFriendUserId(), new AlbumManageUtil.OnFileResponse() {
            @Override
            public void onResult(String url, String path) {
                if (TextUtils.isEmpty(path)) {
                    return;
                }
                GlideUtil.getInstance().load(path, ivUser);
                ObserverThread.create().onBackGroudThread(new Runnable() {
                    @Override
                    public void run() {

                        ChatContentTable q = ChatContentTable.queryRowByTargetId(targetId, Canstants.SINGLE_CHAT);
                        List<ChatTableBean> list = ChatTableBean.query(targetGroup, targetId);
                        FriendTable tableByFriendUserId = FriendTable.getTableByFriendUserId(mFriendTable.getFriendUserId());
                        if (tableByFriendUserId != null) {
                            if (!path.equals(tableByFriendUserId.getFriendAvatarPath())) {
                                tableByFriendUserId.setFriendAvatarPath(path);
                                DbController.getInstance().getWrite().getFriendTableDao().update(tableByFriendUserId);
                            }
                        }
                        if (q != null) {
                            if (!path.equals(q.getTargetAvatarPath())) {
                                q.setTargetAvatarUrl(url);
                                q.setTargetAvatarPath(path);
                                q.setTargetName(mFriendTable.getFriendNickname());
                                DbController.getInstance().getWrite().getChatContentTableDao().update(q);
                            }

                        }
                        if (list != null && !list.isEmpty()) {
                            for (ChatTableBean c : list) {
                                if (!path.equals(c.getChatAvatarPath())) {
                                    c.setChatAvatarUrl(url);
                                    c.setChatAvatarPath(path);
                                    c.setTargetName(mFriendTable.getFriendNickname());
                                    ChatTableBean.update(c);
                                }
                            }
                        }
                    }
                });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUiRefreshNotification(MessageEvent me) {
        if (me == null || me.event() != EventConstants.Event.UI_REFRESH_NOTIFICATION)
            return;
        if (me.action() == EventConstants.Action.DELETE_FRIEND && !isInitiativeDelete) {
            if (!TextUtils.isEmpty(me.data()) && me.data().equals(targetId)) {
                JToast.showShort(this, "对方解除了好友关系");
                finish();
            }
        }
    }

    @Override
    protected void onNettyConnecting() {
        super.onNettyConnecting();
        cbOfflineMsg.setEnabled(false);
    }

    @Override
    protected void onNettyConnectFailure() {
        super.onNettyConnectFailure();
        cbOfflineMsg.setEnabled(false);
    }

    @Override
    protected void onNettyConnectSuccess() {
        super.onNettyConnectSuccess();
        if (NetUtils.isConnected(this)) {
            cbOfflineMsg.setEnabled(true);
        }
    }
}
